package es.udc.pfc.davidparedes.web.pages.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;

import com.google.gson.Gson;

import es.udc.pfc.davidparedes.model.mission.Mission;
import es.udc.pfc.davidparedes.model.store.Store;
import es.udc.pfc.davidparedes.model.storeservice.StoreService;
import es.udc.pfc.davidparedes.model.task.Task;
import es.udc.pfc.davidparedes.model.taskservice.TaskService;
import es.udc.pfc.davidparedes.model.unavailable.Unavailable;
import es.udc.pfc.davidparedes.model.universe.Universe;
import es.udc.pfc.davidparedes.model.userprofile.UserProfile;
import es.udc.pfc.davidparedes.model.userservice.UserService;
import es.udc.pfc.davidparedes.model.util.GlobalNames;
import es.udc.pfc.davidparedes.model.util.InstanceNotFoundException;
import es.udc.pfc.davidparedes.model.vendor.Vendor;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicy;
import es.udc.pfc.davidparedes.web.services.AuthenticationPolicyType;
import es.udc.pfc.davidparedes.web.util.CalendarEvent;
import es.udc.pfc.davidparedes.web.util.UserSession;

@AuthenticationPolicy(AuthenticationPolicyType.MANAGER_OR_ABOVE)
public class DisplayVendorSchedule {
	
	@Property
	private UserProfile userProfile;
	
	@Property
	private Vendor vendor;
	
	@Property
	private Store store;
	
	@Property
	private Universe universe;
	
    @Property
    private List<Task> tasks;
    
    @Property
    private List<Mission> missions;
    
    @Property
    private List<Unavailable> unavailables;
    
    @SessionState(create=false)
    private UserSession userSession;
    
    @Inject
    private UserService userService;
    
    @Inject
    private StoreService storeService;
    
    @Inject
    private TaskService taskService;
    
    @Environmental
    private JavaScriptSupport javaScriptSupport;
    
    @Inject
    private Messages messages;
    
    @InjectPage
    private Home home;
   
    void onActivate(Long id) throws InstanceNotFoundException {
		userProfile = userService.findUserProfile(userSession.getUserProfileId());
		vendor = userService.findVendor(id);
		if (userProfile.getStore() != vendor.getStore()) {
			redirect();
		}
		store = vendor.getStore();
		universe = vendor.getUniverse();
		
		Calendar startMonth = Calendar.getInstance();
		startMonth.add(Calendar.MONTH, GlobalNames.PREVIOUS_LOADED_MONTHS);
		startMonth.set(Calendar.DAY_OF_MONTH, 1);
		startMonth.set(Calendar.HOUR_OF_DAY, 0);
		startMonth.set(Calendar.MINUTE, 0);
		startMonth.set(Calendar.SECOND, 0);
		
		Calendar endMonth = Calendar.getInstance();
		endMonth.add(Calendar.MONTH, GlobalNames.FOLLOWING_LOADED_MONTHS);
		int maxDay = endMonth.getActualMaximum(Calendar.DAY_OF_MONTH);
		endMonth.set(Calendar.DAY_OF_MONTH, maxDay);
		endMonth.set(Calendar.HOUR_OF_DAY, 23);
		endMonth.set(Calendar.MINUTE, 59);
		endMonth.set(Calendar.SECOND, 59);
		
		tasks = taskService.getTasksByDate(vendor.getUserProfileId(), startMonth, endMonth);
		missions = taskService.getMissionsByDate(vendor.getUserProfileId(), startMonth, endMonth);
		unavailables = taskService.getUnavailablesByDate(vendor.getUserProfileId(), startMonth, endMonth);
    }
    
    private String tasksToJSON(){
    	ArrayList<CalendarEvent> array = new ArrayList<CalendarEvent>();
    	CalendarEvent event;
    	for(Task task : tasks){
    		event = new CalendarEvent();
    		event.setId(task.getTaskId());
    		event.setTitle(task.getUniverse().getName()+" ("+task.getType()+")");
    		event.setAllDay(false);
    		event.setStart(task.getStart().getTime());
    		event.setEnd(task.getEnd().getTime());
    		String color = new String();
	        switch (task.getType()) {
		        case GlobalNames.TASK_FESTIVE :
		        	color=GlobalNames.COLOR_YELLOW;
					break;
		        case GlobalNames.TASK_COMPLEMENTARY_FESTIVE :
		        	color=GlobalNames.COLOR_YELLOW;
		        	break;
		        case GlobalNames.TASK_NIGHT :
		        	color=GlobalNames.COLOR_BLACK;
					break;
		        case GlobalNames.TASK_COMPLEMENTARY_NIGHT :
		        	color=GlobalNames.COLOR_BLACK;
					break;
		        case GlobalNames.TASK_LOW :
		        	color=GlobalNames.COLOR_SOFT;
					break;
		        case GlobalNames.TASK_VACATION :
		        	color=GlobalNames.COLOR_SOFT;
					break;
		        case GlobalNames.TASK_ABSENTEEISM :
		        	color=GlobalNames.COLOR_SOFT;
					break;
		        default:
		        	color=GlobalNames.COLOR_BLUE;
	        }
    		event.setBackgroundColor(color);
    		event.setBorderColor(GlobalNames.COLOR_GRAY);
    		event.setUrl("/schedule-manager/user/updatevendortask/" + task.getTaskId());
    		event.setTarget("#updateVendorTask");
    		array.add(event);
    	}
    	
    	for(Mission mission : missions){
    		event = new CalendarEvent();
    		event.setId(mission.getMissionId());
    		event.setTitle(mission.getName()+" ("+mission.getType()+")");
    		event.setAllDay(false);
	        event.setStart(mission.getStart().getTime());
	        event.setEnd(mission.getEnd().getTime());
	        event.setBackgroundColor(GlobalNames.COLOR_PURPLE);
	        event.setBorderColor(GlobalNames.COLOR_GRAY);
	        event.setUrl("/schedule-manager/user/updatevendormission/" + mission.getMissionId());
	        event.setTarget("#updateVendorMission");
	        array.add(event);
    	}
    	
    	for(Unavailable unavailable : unavailables){
    		event = new CalendarEvent();
	        event.setId(unavailable.getUnavailableId());
	        event.setTitle(messages.get("unavailable"));
	        event.setAllDay(false);
	        event.setStart(unavailable.getStart().getTime());
	        event.setEnd(unavailable.getEnd().getTime());
	        event.setBackgroundColor(GlobalNames.COLOR_RED);
	        event.setBorderColor(GlobalNames.COLOR_GRAY);
	        array.add(event);
    	}
    	
	    Gson gson = new Gson();
	    String json = gson.toJson(array);
	    return json;
    }
    
    @AfterRender
    public void afterRender() {
    	javaScriptSupport.addScript("loadCalendar(%s)", tasksToJSON());
    }
    
    private Object redirect() {
    	return home;
    }

}
